<script setup>
import { onBeforeMount, onMounted, reactive, ref } from 'vue';
import { makeMockData } from './utils.js';

const repeatRef = ref(null);

const formData = reactive({
  paginationType: 'Scroll',
  pageSize: 5,
  preloadOffset: 300,
  total: 20,
  itemHeight: 600,
  hasNoData: false,
});

const state = reactive({
  dataList: [],
  hasLoadedAll: false,
  total: 0,
  pageIndex: 0,
});

const onToggleChagne = (v) => {
  reset();
}

const fetchPageData = (index, size, done) => {
  // 模拟获取数据
  const { List, Total } = makeMockData(index, size, formData.total);
  List.map((n, i) => {
    n.bgColor = `rgba(${(i * 10) % 255},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},0.35)`;
  });

  return new Promise(resolve => {
    setTimeout(() => {
      if (formData.hasNoData) {
        state.total = 0;
        state.hasLoadedAll = true;
      } else {
        state.dataList = state.dataList.concat(List || []);
        state.total = Total;
        state.hasLoadedAll = state.dataList.length >= Total;
      }

      if (List && List.length) {
        state.pageIndex = index;
      }
      console.log('fetchPageData', `${state.dataList.length}/${Total}`);
      resolve();
    }, 400);
  });
};

const onScrollLoad = async (index, size, done) => {
  if (formData.hasNoData) {
    done({stop: true, totalCount: 0});
    return;
  }
  try {
    await fetchPageData(index, size, done);
    console.log('done', state.hasLoadedAll, state.total);
    // 获取完数据，必须调用 done 函数，传入是否数据已全部加载
    done({ stop: state.hasLoadedAll, totalCount: state.total });
  } catch (error) {
    console.log(error);
  }
};

const onScrollLoaded = async params => {
  console.log('onScrollLoaded', params);
};

/**
 * 【下拉刷新】时应清空列表数据
 *  - 如果使用 v-model:list="state.dataList" 那么组件内部可以清空列表数据
 *  - 如果使用 :list="state.dataList" 那么请务必在此清空列表数据
 * 另外根据需要清理一下页面其它数据
 */
const onRefresh = async _ => {
  // 根据需要添加页面状态清理
};

const onReset = () => {
  state.dataList = [];
  if (repeatRef.value) {
    console.log('total is ', repeatRef.value.totalCount);
    repeatRef.value.reload();
  }
};

const reset = () => {
  state.dataList = [];
  state.hasLoadedAll = false;
  state.total = 0;

  formData.preloadOffset = 300;
  formData.pageSize = 20;

  onReset();
};

onBeforeMount(() => {});
onMounted(() => {
  console.log('mounted - total is ', repeatRef.value.totalCount);
  setTimeout(() => {
    console.log('delay to show total onMounted', repeatRef.value.totalCount);
  }, 500);
});
</script>

<template>
  <div class="repeat-demo">
    <div class="config-panel q-pa-md">
      <div style="">
        展示无数据的情况：
        <q-toggle v-model="formData.hasNoData" color="green" @update:model-value="onToggleChagne" />
      </div>
      <t-form
        v-if="!formData.hasNoData"
        style="max-width: 600px; margin-bottom: 16px"
      >
        <t-input
          v-model.number="formData.pageSize"
          type="number"
          label="分页条数"
          step="10"
          :min="10"
          :max="50"
          filled
          class="q-my-sm"
          style=""
        />
        <t-input
          fill
          label="总条数"
          v-model="formData.total"
          type="number"
          step="5"
          :min="15"
          :max="100"
          class="q-my-sm"
        ></t-input>
        <t-input
          v-model.number="formData.preloadOffset"
          label="提前加载数据-距离底部的偏移量"
          type="number"
          step="10"
          :min="50"
          :max="500"
          filled
          class="q-my-sm"
          style=""
        />
        <t-input
          v-model.number="formData.itemHeight"
          label="元素高度（上下间距的和）"
          type="number"
          step="50"
          :min="200"
          :max="600"
          filled
          class="q-my-sm"
          style=""
        />
      </t-form>

      <ul class="q-mb-md">
        <li class="q-mt-sm">数据总条数：{{ state.total }}</li>
        <li class="q-mt-sm">当前数据条数：{{ state.dataList.length }}</li>
        <li class="q-mt-sm">当前已获取页：{{ state.pageIndex }}</li>
      </ul>

      <t-button color="primary q-mr-md" @click="reset">重置</t-button>
      <t-button color="primary" @click="onReset">重新加载 Reload</t-button>
      <p>&nbsp;</p>
      <t-separator></t-separator>
      <p>&nbsp;</p>
    </div>

    <t-repeat
      ref="repeatRef"
      v-model:list="state.dataList"
      :offset="formData.preloadOffset"
      :page-size="formData.pageSize"
      :fill-mode="`fixed`"
      :height="`500px`"
      :auto-load="true"
      :pull-refresh="true"
      :show-index-and-count="true"
      :empty-text="`暂无数据`"
      class="t-repeat q-pa-md"
      style="border: 1px solid #e0e2e5"
      @scroll-load="onScrollLoad"
      @scroll-loaded="onScrollLoaded"
      @pull-refresh="onRefresh"
    >
      <template #default>
        <t-item
          v-for="(row, rowIndex) in state.dataList"
          :key="row.id"
          clickable
          v-ripple
          :data-row-index="rowIndex"
        >
          <t-item-section class="flex justify-center">
            <div
              class="text-center"
              :style="{
                background: row.bgColor,
                padding: `${formData.itemHeight/2}px`,
              }"
              >{{ row.description }}</div
            >
          </t-item-section>
        </t-item>
      </template>
    </t-repeat>
  </div>
</template>
